package util

import (
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"strings"
	"time"
)

type Payload struct {
	UserId int64
	Random string
	jwt.StandardClaims
}

func GetJwtToken(userId int64, expire int, key string) (string, error) {
	now := time.Now()
	duration := time.Duration(expire) * time.Second
	expiresAt := now.Add(duration)
	claims := Payload{
		UserId: userId,
		Random: string(RandomCreateBytes(5)),
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: expiresAt.Unix(),
			Issuer:    "dfitc",
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString([]byte(key))
}

/**
验证token
**/
func ValidToken(tokenStr, key string) (*Payload, bool) {
	if strings.Trim(tokenStr, "") == "" {
		return nil, false
	}
	token, err := jwt.ParseWithClaims(tokenStr, &Payload{}, func(token *jwt.Token) (interface{}, error) {
		return []byte(key), nil
	})
	if err != nil {
		return nil, false
	}
	claims, ok := token.Claims.(*Payload)
	//如果token校验没问题
	if err == nil && ok && token.Valid {
		return claims, true
	} else {
		return nil, false
	}
}

/**
  从token中获取userId, 不校验token时效性
*/
func GetTokenUserId(tokenStr, key string) (int64, bool) {
	if strings.Trim(tokenStr, "") == "" {
		return 0, false
	}
	token, err := jwt.ParseWithClaims(tokenStr, &Payload{}, func(token *jwt.Token) (interface{}, error) {
		return []byte(key), nil
	})
	if err != nil {
		fmt.Println("ParseWithClaims info:", err)
	}
	claims, ok := token.Claims.(*Payload)
	if !ok {
		return 0, false
	}
	userId := claims.UserId
	return userId, true
}
